<template>
  <div class="pagination">
    <button @click="changegPageNo(pageNo - 1)" :disabled="pageNo <= 1">
      上一页
    </button>
    <button v-show="pagesArr[0] > 1" @click="changegPageNo(1)">1</button>

    <button v-show="pagesArr[0] > 2">···</button>

    <button
      v-for="item in pagesArr"
      :key="item"
      @click="changegPageNo(item)"
      :class="{ active: pageNo === item }"
    >
      {{ item }}
    </button>

    <button v-show="pagesArr[countedPages - 1] < totalPages - 1">···</button>
    <button
      v-show="pagesArr[countedPages - 1] < totalPages"
      @click="changegPageNo(totalPages)"
    >
      {{ totalPages }}
    </button>
    <button @click="changegPageNo(pageNo + 1)" :disabled="pageNo >= totalPages">
      下一页
    </button>

    <button style="margin-left: 30px">一共 {{ totalPages }}页</button>
  </div>
</template>

<script>
export default {
  name: 'Pagination',
  props: ['pageNo', 'countedPages', 'totalPages'],
  mounted() {
    console.log(this.pageNo, this.countedPages, this.totalPages)
  },
  computed: {
    pagesArr() {
      let arr = []
      //通过计算数据计算出需要展示的数据数组,然后通过遍历的方式渲染到页面中
      // 首先通过当前页码和中间显示页码数量判断展示数组
      let startPage = this.pageNo - Math.floor(this.countedPages / 2)
      let endPage = this.pageNo + Math.floor(this.countedPages / 2)
      // 当生成数据不合理时,需要设置墙
      if (startPage <= 1) {
        endPage = 1 - startPage + endPage
        startPage = 1
      }
      if (endPage >= this.totalPages) {
        // startPage = this.totalPages - this.countedPages + 1
        startPage = startPage - endPage + this.totalPages
        endPage = this.totalPages
      }
      // 遍历生成展示数组
      for (let index = startPage; index <= endPage; index++) {
        arr.push(index)
      }
      return arr
    },
  },
  methods: {
    // 修改父的pageNo
    changegPageNo(index) {
      this.$emit('changePage', index)
    },
  },
}
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>
